package org.example.service.impl;

import org.example.dao.DeptDao;
import org.example.dao.LogDao;
import org.example.dao.impl.DBUtil;
import org.example.dao.impl.DeptDaoImpl;
import org.example.dao.impl.LogDaoImpl;
import org.example.entity.Dept;
import org.example.entity.Log;
import org.example.service.DeptService;

import java.sql.Connection;
import java.sql.SQLException;

public class DeptServiceImpl implements DeptService {

    DeptDao deptDao = new DeptDaoImpl();
    LogDao logDao = new LogDaoImpl();

    /**
     * 添加部门，同时要添加日志记录
     * 需要涉及到事务的操作
     * @param dept
     */
    @Override
    public void saveDept(Dept dept) {
        Connection conn = DBUtil.getConn();
        try {
            conn.setAutoCommit(false);
            deptDao.addDept(conn,dept);
            Log log = new Log();
            log.setLogDesc("添加了一个部门，部门名称是" + dept.getDeptName() + "操作员是张三");
            log.setOperator("zhangsan");
            logDao.addLog(conn,log);
            conn.commit();
        }catch (SQLException ex) {
            ex.printStackTrace();
            System.out.println("出现异常，异常信息" + ex.getMessage());
            try {
                conn.rollback();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }finally {
            DBUtil.close(conn,null,null);
        }
    }
}
